﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.Swagger;

namespace orz.mouxianyu.Extensions
{
    public static class JwtAuthenticationExtensions
    {
        /// <summary>
        /// 配置 jwt 认证 Startup 辅助类
        /// </summary>
        /// <returns></returns>
        public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, IConfiguration Configuration)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,

                        ValidIssuer = "orz.mouxianyu",
                        ValidAudience = "orz.mouxianyu",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:SecurityKey"]))
                    };
                });

            // Claim 角色 映射 到管道中
            services.AddAuthorization(options =>
            {
                options.AddPolicy("CoreApiAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "admins");
                });
                options.AddPolicy("CoreApiUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "users");
                });

            });

            return services;
        }
    }
}
